package com.itcast.util;

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.EuclideanDistanceSimilarity;
import org.apache.mahout.cf.taste.impl.similarity.UncenteredCosineSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
import org.apache.mahout.common.RandomUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class ItemCF{
    final static int NEIGHBORHOOD_NUM = 6;
    final static int RECOMMENDER_NUM = 6;
    public static void main(String[] args) throws IOException,TasteException
    {


        String file = "src/data/test.txt";

        DataModel model = new FileDataModel(new File(file));
        //余弦相似度
        ItemSimilarity itemSimilarity = new UncenteredCosineSimilarity(model);
        //定义推荐引擎
        Recommender recommender =new GenericItemBasedRecommender(model, itemSimilarity);
        //获取物品迭代器
        LongPrimitiveIterator itemIDIterator = model.getItemIDs();
        //遍历所有物品
        while(itemIDIterator.hasNext()){
            System.out.println("==================================================");
            Long itermID=itemIDIterator.next();
            LongPrimitiveIterator otherItemIDIterator=model.getItemIDs();
            //打印物品相似度
            while (otherItemIDIterator.hasNext()){
                Long otherItermID=otherItemIDIterator.next();
                System.out.println("物品 "+itermID+" 与物品 "+otherItermID+" 的相似度为： "+itemSimilarity.itemSimilarity(itermID,otherItermID));
            }
        }
        //获取用户迭代器
        LongPrimitiveIterator userIDIterator =model.getUserIDs();
        //遍历用户
        while(userIDIterator.hasNext()){
            //获取用户
            Long userID=userIDIterator.next();
            //获取用户userID的推荐列表
            List<RecommendedItem> itemList= recommender.recommend(userID,6);
            if(itemList.size()>0){
                for(RecommendedItem item:itemList){
                    System.out.println("用户 "+userID+" 推荐物品 "+item.getItemID()+",物品评分 "+item.getValue());
                }
            }else {
                System.out.println("用户 "+userID+" 无任何物品推荐");
            }
        }
    }
}
